package zhtt.example.predicate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.List;

@Component
public class TimeAfterRoutePredicateFactory extends AbstractRoutePredicateFactory<TimeAfterRoutePredicateFactory.Config> {
    private static final Logger logger = LoggerFactory.getLogger(TimeAfterRoutePredicateFactory.class);

    public TimeAfterRoutePredicateFactory() {
        super(Config.class);
        logger.info("TimeAfterRoutePredicateFactory initialized");
    }

    @Override
    public GatewayPredicate apply(Config config) {
        LocalTime time = config.getTime();
        logger.info("Parsed time: {}", time);

        return exchange -> {
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime todayAtTime = LocalDateTime.of(now.toLocalDate(), time);

            if (now.isBefore(todayAtTime)) {
                // 如果当前时间在指定时间之前，则计算明天的相同时间
                todayAtTime = todayAtTime.plusDays(1);
            }

            ZonedDateTime zonedDateTime = ZonedDateTime.of(todayAtTime, ZoneId.systemDefault());
            return Mono.just(now.isAfter(todayAtTime)).block();
        };
    }

    public static class Config {
        private LocalTime time;

        public LocalTime getTime() {
            return time;
        }

        public void setTime(String time) {
            System.out.println(time);
            this.time = LocalTime.parse(time);
            System.out.println(this.time);
        }
    }
}
